package game
import (
	"fmt"
	"db"
	"github.com/name5566/leaf/log"
	"strings"
	"strconv"
	"message"
	"github.com/golang/protobuf/proto"
	"config"
	"time"
)

// 检查玩家是否具备gm权限
func (self *User)checkPermission() bool {
	return true
}

var botIndex = 0

func createBot() *User {
	botIndex++

	bot := new(User)
	bot.data = new(db.UserData)
	bot.data.Account = "bot"
	bot.data.CreateTime = time.Now().Unix()
	bot.data.TotalCount = 0
	bot.data.WinCount = 0
	bot.data.TotalMoney = config.INIT_TOTAL_MONEY
	bot.data.UserID = botIndex
	bot.data.Name = fmt.Sprintf("Bot%v", bot.ID())
	bot.data.TotalMoney = 100000
	bot.onInit()
	bot.bot = true

	return bot
}

// 添加机器人到当前房间(GM)
func (self *User)addBot(count int) {
	// 必须要进入房间才能添加机器人
	if self.room == nil {
		return
	}

	hall := getHall(self.hallID)
	if hall == nil {
		return
	}

	for i := 0; i < count; i++ {
		// TODO 创建机器人
		bot := createBot()
		bot.hallID = self.hallID
		bot.roomID = self.roomID
		bot.room = self.room

		hall.onPlayerEnterHall(bot, false)
		self.room.onPlayerEnterRoom(bot, true, false)
	}
}

// 请求在指定位置添加机器人
func (self *User) addBotAtPosition(pos int) {
	if self.room == nil {
		return
	}

	hall := getHall(self.hallID)
	if hall == nil {
		return
	}

	bot := createBot()
	bot.hallID = self.hallID
	bot.roomID = self.roomID
	bot.room = self.room

	hall.onPlayerEnterHall(bot, false)
	self.room.onPlayerEnterRoom(bot, false, false)
	self.room.onPlayerSitDown(bot, pos)
}

// c-s 通用GM命令接口
func (self *User) reqGMCommand(command string) {
	log.Debug("reqGMCommand:  %v  %v", self.str(), command)

	args := strings.Split(command, " ")
	switch args[0] {
	case "killbot":
		// 删除所有机器人
		if self.room != nil {
			self.room.onKillBots()
		}
	case "addmoney":
		// 增加金钱
		value, _ := strconv.Atoi(args[1])
		self.data.TotalMoney += int64(value)
		self.money += value
		data := &message.S2C_AttributeChanged{}
		data.Attribute = append(data.Attribute, &message.UserAttribute{Type: message.PlayerAttributeType_PLAYER_ATTR_MONEY.Enum(), Value:proto.Int64(int64(self.money))})
		data.Attribute = append(data.Attribute, &message.UserAttribute{Type: message.PlayerAttributeType_PLAYER_ATTR_TOTAL_MONEY.Enum(), Value:proto.Int64(self.data.TotalMoney)})
		self.SendMsg(message.MSG_ATTRIBUTE_CHANGED, data)
	case "beginturn":
		// 开始新局
		if self.room != nil {
			self.room.beginTurn()
		}
	case "addbot":
		// 添加机器人
		value, _ := strconv.Atoi(args[1])
		self.addBot(value)
	case "addbotpos":
		// 在一个位置添加机器人
		value, _ := strconv.Atoi(args[1])
		self.addBotAtPosition(value)
	case "autoplay":
		if self.room != nil {
			self.room.botAutoPlay()
		}
	case "botaction":
		if self.room != nil {
			value, _ := strconv.Atoi(args[1])
			action := message.PokerAction(value)
			self.room.botAction(action)
		}
	}
}